using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Permissions;
using Microsoft.Robotics.PhysicalModel.Proxy;

using Microsoft.Dss.Core.DsspHttpUtilities;
using System.Collections.Specialized;

using W3C.Soap;
using submgr = Microsoft.Dss.Services.SubscriptionManager;
using vex = VEXRobotics.Proxy;
using r = Microsoft.Robotics;

/* Notes on VEX Servo
 *   Identifier must be the Servo port number on the VEX. Range: 1 - 8.
 */
namespace VEXService.Servo
{
    // Summary:
    //     State Definition for the Motor Service
    [DataContract]
    [Description("The VEX configuration state.")]
    public class VEXServoState : IDssSerializable, ICloneable
    {
        private vex.MotorPort _MotorPort;
        private string _Name;
        private double _CurrentAngle;
        private Pose _Pose;
        private DateTime _TimeStamp;

        public VEXServoState()
        {
            _Pose = new Pose();
        }

        public VEXServoState(string name, vex.MotorPort hardwareIdentifier, Pose pose)
        {
            _Name = name;
            _MotorPort = hardwareIdentifier;
            _Pose = pose;
            _CurrentAngle = 0;
        }

        [DataMember]
        [Description("Identifies the hardware port of the servo.")]
        public vex.MotorPort MotorPort
        {
            get { return _MotorPort; }
            set { this._MotorPort = value; }
        }

        [DataMember]
        [Description("Specifies the descriptive identifier for the motor.")]
        public string Name
        {
            get { return _Name; }
            set { this._Name = value; }
        }

        [DataMember]
        [Description("Indicates the current angle; range is -135.0/180.0*PI to 135.0/180.0*PI.")]
        public double CurrentAngle
        {
            get { return _CurrentAngle; }
            set { this._CurrentAngle = value; }
        }

        [DataMember]
        [Description("The position and orientation of the servo.")]
        public Pose Pose
        {
            get { return _Pose; }
            set { this._Pose = value; }
        }

        //
        // Summary:
        //     Timestamp of this sample
        [DefaultValue(typeof(DateTime), "0001-01-01T00:00:00")]
        [Description("Identifies the timestamp of the servo reading.")]
        [Browsable(false)]
        [DataMember(Order = -1, XmlOmitDefaultValue = true)]
        public DateTime TimeStamp
        {
            get { return _TimeStamp; }
            set { _TimeStamp = value; }
        }


        #region IDssSerializable

        /// <summary>
        /// Copy To Analog Input sensor state
        /// </summary>
        public virtual void CopyTo(IDssSerializable target)
        {
            VEXServoState typedTarget = target as VEXServoState;

            if (typedTarget == null)
                throw new ArgumentException("CopyTo({0}) requires type {0}", this.GetType().FullName);

            typedTarget.CurrentAngle = this.CurrentAngle;
            typedTarget.MotorPort = this.MotorPort;
            typedTarget.Name = this.Name;
            typedTarget.Pose = this.Pose;
            typedTarget.TimeStamp = this.TimeStamp;
        }

        /// <summary>
        /// Clone the VEX Servo State
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            VEXServoState clone = new VEXServoState();

            clone.CurrentAngle = this.CurrentAngle;
            clone.MotorPort = this.MotorPort;
            clone.Name = this.Name;
            clone.Pose = this.Pose;
            clone.TimeStamp = this.TimeStamp; 

            return clone;
        }

        /// <summary>
        /// Serialize
        /// </summary>
        public virtual void Serialize(System.IO.BinaryWriter writer)
        {
            writer.Write(this.CurrentAngle);
            writer.Write((int)this.MotorPort);
            writer.Write(this.Name);
            Pose.Serialize(writer);
            Microsoft.Dss.Services.Serializer.BinarySerializationHelper.SerializeDateTime(TimeStamp, writer);
        }

        /// <summary>
        /// Deserialize
        /// </summary>
        public virtual object Deserialize(System.IO.BinaryReader reader)
        {
            this.CurrentAngle = reader.ReadDouble();
            this.MotorPort = (vex.MotorPort)reader.ReadInt32();
            Name = reader.ReadString();
            Pose.Deserialize(reader);
            TimeStamp = Microsoft.Dss.Services.Serializer.BinarySerializationHelper.DeserializeDateTime(reader);

            return this;
        }
        #endregion
    }

    /// <summary>
    /// Get the state
    /// </summary>
    [DataContract]
    public class Get : Get<GetRequestType, PortSet<VEXServoState, Fault>>
    {
    }

    /// <summary>
    /// Replace the state
    /// </summary>
    [DataContract]
    public class Replace : Replace<VEXServoState, PortSet<DefaultReplaceResponseType, Fault>>
    {
        /// <summary>
        /// Default Constructor
        /// </summary>
        public Replace()
        {
        }

        /// <summary>
        /// Initialization Constructor
        /// </summary>
        public Replace(VEXServoState config)
        {
            this.Body = config;
        }
    }

    // Summary:
    //     Sets (or indicates a change to) the motor's power setting.
    [DataContract]
    public class SetServoAngleRequest
    {
        double _angleInDegrees;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public SetServoAngleRequest()
        {
        }

        /// <summary>
        /// Initialization Constructor
        /// </summary>
        public SetServoAngleRequest(double angle)
        {
            this._angleInDegrees = angle;
        }

        [DataMember]
        [Description("Desired angle; range is -135.0/180.0*PI to 135.0/180.0*PI.")]
        public double AngleInDegrees
        {
            get { return _angleInDegrees; }
            set { this._angleInDegrees = value; }
        }
    }
    [DataContract]
    public class SetServoAngle : Update<SetServoAngleRequest, PortSet<DefaultUpdateResponseType, Fault>>
    {
        public SetServoAngle()
        {
        }
        public SetServoAngle(SetServoAngleRequest body)
        {
            this.Body = body;
        }
    }

    [ServicePort]
    public class VEXServoOperations : PortSet<
        DsspDefaultLookup,
        DsspDefaultDrop,
        Servo.Get,
        Servo.Replace,
        Servo.SetServoAngle,
        HttpGet,
        HttpPost>
    { }

    [Contract(VEXService.Servo.Contract.Identifier)]
    [DisplayName("VEX Servo")]
    [Description("Provides access to the VEX Servo.")]
    [DssCategory(vex.VEXCategories.VEX)]
    public class VEXServoService : DsspServiceBase
    {
        /// <summary>
        /// XSLT Transform to use for display
        /// </summary>
        [EmbeddedResource("VEXService.Config.Servo.xslt")]
        private string _transform = null;

        /// <summary>
        /// Servo state
        /// </summary>
        [InitialStatePartner(Optional = true, ServiceUri = ServicePaths.Store + @"/VEX.Servo.Config.xml")]
        Servo.VEXServoState _State;

        /// <summary>
        /// Service port
        /// </summary>
        [ServicePort("VEX/Servo", AllowMultipleInstances = true)]
        private VEXServoOperations _mainPort = new VEXServoOperations();

        /// <summary>
        /// Port to talk with the VEX controller
        /// </summary>
        [Partner("VEX", Contract = vex.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate,
            Optional = false)]
        private vex.VEXOperations _vexPort = new vex.VEXOperations();
        private vex.VEXOperations _vexNotificationPort = new vex.VEXOperations();

        /// <summary>
        /// HTTP helper
        /// </summary>
        DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort();

        /// <summary>
        /// Subscription manager
        /// </summary>
        [Partner("SubMgr", Contract = submgr.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.CreateAlways,
            Optional = false)]
        private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="creationPort"></param>
        public VEXServoService(DsspServiceCreationPort creationPort)
            :
                base(creationPort)
        {
        }

        /// <summary>
        /// Startup
        /// </summary>
        protected override void Start()
        {
            LogVerbose(LogGroups.Console, "Configuring VEX Servo... ");

            #region Initialize Service State
            if (_State == null)
            {
                _State = new VEXServoState();
                SaveState(_State);
            }
            #endregion

            base.Start();

            #region Initialize Service State
            // Reset the controller to know about our configuration
            Port<bool> donePort = new Port<bool>();
            SpawnIterator<Port<bool>>(donePort, InitializeKnownConnection);
            Activate(Arbiter.Receive(false, donePort,
                delegate(bool success)
                {
                    if (success)
                    {
                        // display HTTP service Uri
                        LogInfo(LogGroups.Console, "Service uri: ");
                    }
                    else
                    {
                        LogError(LogGroups.Console, "VEX Servo service failed to start.");
                        _mainPort.Post(new DsspDefaultDrop());
                    }
                }));
            #endregion

            // Needed for HttpPost
            _httpUtilities = DsspHttpUtilitiesService.Create(Environment);
        }

        /// <summary>
        /// Find a valid motor to hook up to
        /// </summary>
        /// <returns></returns>
        private IEnumerator<ITask> InitializeKnownConnection(Port<bool> resultPort)
        {
            bool serviceSuccess = true;

            if (_State.MotorPort == vex.MotorPort.MotorPort_None)
            {
                LogError(_State.Name + ": No motor port selected");
                serviceSuccess = false;
            }
            else
            {
                vex.SelectiveMotorConfigure motorConfig = new vex.SelectiveMotorConfigure();
                motorConfig.Body.Motor = _State.MotorPort;
                motorConfig.Body.Type = "Servo";

                _vexPort.Post(motorConfig);
                yield return Arbiter.Choice(motorConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });

                // Start listening
                if (serviceSuccess)
                {
                    // Subscribe to the VEX and wait for a response
                    SubscribeRequestType request = new SubscribeRequestType();
                    yield return
                        Arbiter.Choice(_vexPort.Subscribe(request, _vexNotificationPort),
                            delegate(SubscribeResponseType Rsp)
                            {
                                // Update our state with subscription status
                                serviceSuccess = true;
                            },
                            delegate(Fault fault)
                            {
                                LogError("Servo subscription failed", fault);
                                serviceSuccess = false;
                            }
                        ); 
                }

                // Subscribe to VEX for notifications
                if (serviceSuccess)
                {
                    yield return Arbiter.Choice(
                        _vexPort.Subscribe(_vexNotificationPort, typeof(vex.Update)),
                        EmptyHandler,
                        delegate(Fault f)
                        {
                            serviceSuccess = false;
                        });
                }

                if (serviceSuccess)
                {
                    base.MainPortInterleave.CombineWith(new Interleave(
                        new ExclusiveReceiverGroup(
                            Arbiter.Receive<vex.Update>(true, _vexNotificationPort, SensorNotificationHandler)
                        ),
                        new ConcurrentReceiverGroup()));
                }
            }

            resultPort.Post(serviceSuccess);
            yield break;
        }

        /// <summary>
        /// Handle sensor update message from VEX
        /// </summary>
        private void SensorNotificationHandler(vex.Update notify)
        {
            if (_State.MotorPort != vex.MotorPort.MotorPort_None)
            {
                // Update state
                int newValue;
                newValue = notify.Body.Motors.Motors[(int)_State.MotorPort - 1].Value;
                int curPower = (int)Math.Round(_State.CurrentAngle * 127.0 / 1.5707963267948966192313216916398) + 127;
                bool changed = (curPower != newValue);
                _State.TimeStamp = DateTime.Now;
                _State.CurrentAngle = (newValue -127.0) * 1.5707963267948966192313216916398 / 127.0;
                _State.CurrentAngle = Math.Round(_State.CurrentAngle * 1000.0) / 1000.0;

                // Notify subscribers on any state change
                if (changed)
                {
                    SendNotification<Replace>(_subMgrPort, _State);
                }
            }
        }

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public IEnumerator<ITask> GetHandler(Servo.Get get)
        {
            get.ResponsePort.Post(_State);
            yield break;
        }

        /// <summary>
        /// Get the state to HTTP display
        /// </summary>
        /// <param name="httpGet">Response port to post the state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            httpGet.ResponsePort.Post(new HttpResponseType(
                HttpStatusCode.OK,
                _State,
                _transform)
            );
            yield break;
        }

        /// <summary>
        /// HttpPost Handler
        /// </summary>
        /// <param name="submit"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost)
        {
            // Use helper to read form data
            ReadFormData readForm = new ReadFormData(httpPost);
            _httpUtilities.Post(readForm);

            // Wait for result
            Activate(Arbiter.Choice(readForm.ResultPort,
                delegate(NameValueCollection parameters)
                {
                    if (parameters["Name"] != null)
                    {
                        _State.Name = parameters["Name"];
                    }
                    if (parameters["Angle"] != null)
                    {
                        double angle = 0;
                        double.TryParse(parameters["Angle"], out angle);
                        _State.CurrentAngle = angle;
                        _State.CurrentAngle = Math.Round(_State.CurrentAngle * 1000.0) / 1000.0;
                        _State.TimeStamp = DateTime.Now;

                        Servo.SetServoAngle powerReq = new Servo.SetServoAngle();
                        powerReq.Body.AngleInDegrees = angle;
                        _mainPort.Post(powerReq);
                        Activate(
                            Arbiter.Choice(
                                Arbiter.Receive<DefaultUpdateResponseType>(false, powerReq.ResponsePort,
                                    delegate(DefaultUpdateResponseType response)
                                    {
                                        HttpPostSuccess(httpPost);
                                    }),
                                Arbiter.Receive<Fault>(false, powerReq.ResponsePort,
                                    delegate(Fault fault)
                                    {
                                        HttpPostFailure(httpPost, fault.Reason[0].Value);
                                    })
                            )
                        );
                    }
                    else
                    {
                        HttpPostSuccess(httpPost);
                    }
                },
                delegate(Exception fault)
                {
                    LogError(fault.Message);
                    HttpPostFailure(httpPost, fault.Message);
                })
            );

            yield break;
        }

        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _State, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        private static void HttpPostFailure(HttpPost httpPost, string failureReason)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.ExpectationFailed, failureReason);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Replace the state with the given update
        /// </summary>
        /// <param name="replace">Replacement state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> ReplaceHandler(Servo.Replace replace)
        {
            _State = replace.Body;
            SaveState(_State);
            replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Set the Servo angle
        /// </summary>
        /// <param name="setServoAngle"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> SetServoAngleHandler(Servo.SetServoAngle setServoAngle)
        {
            // Update state
            _State.CurrentAngle = setServoAngle.Body.AngleInDegrees;
            _State.CurrentAngle = Math.Round(_State.CurrentAngle * 1000.0) / 1000.0;
            _State.TimeStamp = DateTime.Now;

            // Convert power
            int power = (int)Math.Round(_State.CurrentAngle * 127.0 / 1.5707963267948966192313216916398);
            power += 127;
            if (power < 0)
                power = 0;
            if (power > 255)
                power = 255;

            // Send hardware specific Servo data
            vex.SetMotor servoData = new vex.SetMotor();
            servoData.Motor = _State.MotorPort;
            servoData.Power = power;

            vex.SetMotorList motorList = new vex.SetMotorList();
            motorList.Motors = new List<vex.SetMotor>();
            motorList.Motors.Add(servoData);

            Activate(Arbiter.Choice(_vexPort.SetMotorRequest(motorList),
                delegate(DefaultUpdateResponseType status)
                {
                },
                delegate(Fault fault)
                {
                }
            ));

            // Reply to sender
            setServoAngle.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }

    }

    /// <summary>
    /// VEX Servo Contract 
    /// </summary>
    public sealed class Contract
    {
        public const string Identifier = "http://schemas.vexrobotics.com/2011/09/vexservice.servo.html";
    }

}
